﻿using StockMarketTool.Helper;
using StockMarketTool.Model;
using StockMarketTool.ViewModel;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;

namespace StockMarketTool
{
    /// <summary>
    /// Setting.xaml 的交互逻辑
    /// </summary>
    public partial class Setting : Window
    {
        private static volatile Setting instance = null;
        private static volatile object lockobj = new object();
        private CodeValueModel settingNotifyItem = null;
        public static Setting GetInstance(MainViewModel vm)
        {
            if (instance == null)
            {
                lock (lockobj)
                {
                    if (instance == null)
                        instance = new Setting(vm);
                }
            }
            return instance;
        }
        private Setting(MainViewModel vm)
        {
            InitializeComponent();
            this.DataContext = vm;
        }

        private void Exit_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            this.Hide();
            e.Handled = true;
        }

        private void border_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
                this.DragMove();
        }

        private void Img_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Image img = sender as Image;
            if (img == null || img.Tag == null)
                return;
            CodeValueModel model = img.Tag as CodeValueModel;
            if (model == null)
            {
                return;
            }
            (this.DataContext as MainViewModel).SetShowValue(model.Code);
            e.Handled = true;
        }

        private void ImgDel_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            MainViewModel mvm = this.DataContext as MainViewModel;
            if (mvm == null)
                return;
            Image img = sender as Image;
            if (img == null || img.Tag == null)
                return;
            CodeValueModel model = img.Tag as CodeValueModel;
            if (model == null)
            {
                return;
            }
            mvm.SelectedValue = model;

            Border bd = VisualTreeHelpers.FindVisualParent<Border>(img);
            if (bd != null)
            {
                bd.RenderTransformOrigin = new Point(0, 0.5);
                bd.RenderTransform = new ScaleTransform() { ScaleX = 1, ScaleY = 1 };
                RunStb(bd, new Duration(TimeSpan.FromMilliseconds(200)), "(Border.RenderTransform).(ScaleTransform.ScaleX)", () =>
                {
                    mvm.DeleteCommand.Execute(null);
                });
            }
            else
                mvm.DeleteCommand.Execute(null);
            e.Handled = true;
        }

        private void CollectionViewSource_Filter(object sender, FilterEventArgs e)
        {
            string keyword = this.tbCode.Text.ToLower().Trim();
            StockModel stock = e.Item as StockModel;
            if (stock != null)
            {
                if (string.IsNullOrEmpty(keyword))
                {
                    e.Accepted = false;
                }
                else
                {
                    //有关键字、筛选名称或编码
                    e.Accepted = stock.name.Contains(keyword) || stock.symbol.Contains(keyword) || stock.code.Contains(keyword);
                }
            }
        }

        private void TbCode_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (String.IsNullOrWhiteSpace(this.tbCode.Text))
            {
                this.popStockList.IsOpen = false;
            }
            else
            {
                this.popStockList.IsOpen = true;
            }
            CollectionViewSource StockSource = (CollectionViewSource)this.FindResource("StockSource");
            StockSource.View.Refresh();//刷新View
        }

        private void TbCode_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Up)
            {
                if (this.lb.Items.Count <= 0)
                    return;
                int idx = lb.SelectedIndex;
                if (idx == -1)
                {
                    lb.SelectedItem = lb.Items[lb.Items.Count - 1];
                }
                else
                {
                    if (idx == 0)
                    {
                        lb.SelectedItem = lb.Items[lb.Items.Count - 1];
                        idx = lb.Items.Count;
                    }
                    lb.SelectedItem = lb.Items[idx - 1];
                }
                lb.ScrollIntoView(lb.SelectedItem);
            }
            else if (e.Key == Key.Down)
            {
                if (this.lb.Items.Count <= 0)
                    return;
                int idx = lb.SelectedIndex;
                if (idx == -1)
                {
                    lb.SelectedItem = lb.Items[0];
                }
                else
                {
                    if (idx == lb.Items.Count - 1)
                    {
                        lb.SelectedItem = lb.Items[0];
                    }
                    else
                    {
                        lb.SelectedItem = lb.Items[idx + 1];
                    }
                }
                idx = lb.SelectedIndex;
                lb.ScrollIntoView(lb.SelectedItem);
            }
            else if (e.Key == Key.Enter)
            {
                SetStock();
                if (!this.tbCode.Text.ToLower().Contains("sh") && !this.tbCode.Text.ToLower().Contains("sz"))
                {
                    MessageBox.Show("股票代码需带上分类前缀，上证：sh；深成：sz。比如上证综合指数(000001)：sh000001；深圳成指数(399001)：sz399001");
                }
                else
                    (this.DataContext as MainViewModel).AddCommand.Execute(null);
                this.tbCode.Focus();
            }
        }
        private void SetStock()
        {
            StockModel model = lb.SelectedItem as StockModel;
            if (model == null)
                return;
            this.tbCode.Text = model.symbol;
        }

        private void ListBox_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            SetStock();
            if (!this.tbCode.Text.ToLower().Contains("sh") && !this.tbCode.Text.ToLower().Contains("sz"))
            {
                MessageBox.Show("股票代码需带上分类前缀，上证：sh；深成：sz。比如上证综合指数(000001)：sh000001；深圳成指数(399001)：sz399001");
            }
            else
                (this.DataContext as MainViewModel).AddCommand.Execute(null);
            this.tbCode.Focus();
            e.Handled = true;
        }


        private void RunStb(UIElement ele, Duration duration, string properPath, Action completed = null)
        {
            Storyboard stb = new Storyboard();
            DoubleAnimation da = new DoubleAnimation();
            da.BeginTime = new TimeSpan();
            da.Duration = duration;
            da.To = 0;
            Storyboard.SetTarget(da, ele);
            Storyboard.SetTargetProperty(da, new PropertyPath(properPath));
            stb.Children.Add(da);
            if (completed != null)
                stb.Completed += (s, e) =>
                {
                    completed.Invoke();
                };
            stb.Begin();
        }

        private void imgNotify_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Image img = sender as Image;
            if (img == null || img.Tag == null)
                return;
            CodeValueModel model = img.Tag as CodeValueModel;
            if (model == null)
            {
                return;
            }
            this.settingNotifyItem = model;
            this.tblNotifyName.Text = settingNotifyItem.Name;
            this.cbNotifyType.SelectedIndex = (int)settingNotifyItem.NotifyType;
            this.tbNotifyValue.Text = settingNotifyItem.NotifyValue.ToString();
            RunStb("stbShowSetNotify");
        }

        private void btnApplyNotifySetting_Click(object sender, RoutedEventArgs e)
        {
            MainViewModel mvm = this.DataContext as MainViewModel;
            if (mvm == null)
                return;
            double v = 0.0d;
            if(!double.TryParse(this.tbNotifyValue.Text,out v))
            {
                AlertMsgWin.GetInstance().Show("值非法");
                return;
            }
            this.settingNotifyItem.NotifyType = (NotifyTypeEnums)this.cbNotifyType.SelectedIndex;
            this.settingNotifyItem.NotifyValue = v;
            this.settingNotifyItem.PlayNotifyMusic = (bool)this.rbtEnableMusic.IsChecked;
            if (this.settingNotifyItem.NotifyType == NotifyTypeEnums.价格)
                this.settingNotifyItem.IsLestThen = this.settingNotifyItem.CurValue >= v;
            mvm.SetNotifyItem(this.settingNotifyItem);
            RunStb("stbShowSetting");
        }

        private void btnCancelNotifySetting_Click(object sender, RoutedEventArgs e)
        {
            RunStb("stbShowSetting");
        }

        private void RunStb(string key)
        {
            Storyboard stb = FindResource(key) as Storyboard;
            if (stb != null)
                stb.Begin();
        }

        private void btnTestMusic_Click(object sender, RoutedEventArgs e)
        {
            AlertMsgWin.GetInstance().Show("测试",true);
        }
    }
}
